<?php

class EventController extends AdminController {

    public $parentUrl;

    public function init() {
        parent::init();
        $this->parentUrl = $this->module->id . '/' . Yii::app()->getController()->getId();
    }

    /* Object Event Category */

    public function actionEvent_category() {
        //Get all records
        $event_category = EventCategory::model()->findAll();
        $this->render('event_category', array('data' => $event_category));
    }

    public function actionCreate_event_category() {
        $event_category = new EventCategory();
                
        if (isset($_POST['EventCategory'])) {
            $event_category->attributes = $_POST['EventCategory'];
                
            $objectFile = CUploadedFile::getInstance($event_category,'icon');
            // var_dump($objectFile);die();
            if ($objectFile != null) {
                $icon = file_get_contents($objectFile->tempName);
                $event_category->icon = base64_encode($icon);
            }
            
            $event_category->created_date = date('Y-m-d H:i:s');
            $event_category->save();
            $this->redirect(Yii::app()->createAbsoluteUrl('bookingsystem/event/event_category'));
        }
        $this->render('create_event_category', array('model' => $event_category));
    }

    public function actionEdit_cat($id) {
        // Get records with id 
        $model_event_cat = EventCategory::model()->findByPk($id);
                
        if (isset($_POST['EventCategory'])) {
            $model_event_cat->attributes = $_POST['EventCategory'];
            
            $objectFile = CUploadedFile::getInstance($model_event_cat,'icon');
            // var_dump($objectFile);die();
            if ($objectFile != null) {
                $icon = file_get_contents($objectFile->tempName);
                $model_event_cat->icon = base64_encode($icon);
            }
            
            $model_event_cat->updated_date = date('Y-m-d H:i:s');
            $model_event_cat->save();
            $this->redirect(Yii::app()->createAbsoluteUrl('bookingsystem/event/event_category'));
        }
        $this->render('edit_cat', array('model' => $model_event_cat));
    }

    public function actionDelete_cat($id) {
//        $model_event_cat = EventCategory::model()->findByPk($id);
//        if (isset($model_event_cat)) {
//            $model_event_cat->delete();
//            $this->redirect(Yii::app()->createAbsoluteUrl('bookingsystem/event/event_category'));
//        }
        
        try
        {
            if(Yii::app()->request->isPostRequest)
            {
                // we only allow deletion via POST request
                if($model = $this->loadModel($id))
                {
                    if($model->delete())
                    {
                        Yii::log("Delete record ".  print_r($model->attributes, true), 'info');
                    }

                }

                // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
                if(!isset($_GET['ajax']))
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
            }
            else
                {
                    Yii::log("Invalid request. Please do not repeat this request again.");
                    throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
                }
            }
        catch (Exception $e)
        {
            Yii::log("Exception ".  print_r($e, true), 'error');
            throw  new CHttpException("Exception ".  print_r($e, true));
        }        
    }

/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
            try
            {
		if(isset($_POST['ajax']) && $_POST['ajax']==='pages-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
            }
            catch (Exception $e)
            {
                Yii::log("Exception ".  print_r($e, true), 'error');
                throw  new CHttpException("Exception ".  print_r($e, true));
            }
	}
    
    public function actionView($id) {
        try {
            $this->render('view', array(
                'model' => $this->loadModel($id), 'parentUrl' => $this->parentUrl
            ));
        } catch (Exception $e) {
            Yii::log("Invalid request. Please do not repeat this request again.");
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    public function actionCreate() {
        try {
            $model = new Event();
            $translate = new Translate();
            $item = new Item('search');
            $item->unsetAttributes();
            if(isset($_GET['Item'])) {
                $item->attributes = $_GET['Item'];
            }
            
            if (isset($_POST['Event'])) {
                $model->attributes = $_POST['Event'];
                $model->status = STATUS_ACTIVE;
                // status 0 is Open.
                // $model->status = STATUS_ACTIVE; 
                //Get Instance Image Upload File
                $objectFile = CUploadedFile::getInstance($model, 'fileImage');
                //Check object file and rename image.
                if ($objectFile)
                    $model->fileImage = 'map_' . md5(time()) . '.' . $objectFile->getExtensionName();
                // Validate Model Event 
                $model->validate();
                //Validate success: system will be return none error
                if (!$model->hasErrors()) {
                    //Get tag form client
                    $tagTmp = (isset($_POST['Event']['tag'])) ? $_POST['Event']['tag'] : '';
                    $tag = MyFunctionCustom::addMoreTag($model, $tagTmp);
                    $model->tag = (is_null($tag)) ? json_encode(array()) : json_encode($tag);
                    $model->event_code = trim($_POST['Event']['event_code']);
                    //Upload Seat Map to server
                    if ($objectFile) {
                        $model->map = MyFunctionCustom::saveMap($model, $objectFile);
                    }
                    //Remove language element sothat insert db for multi language -- Contact HongTa to resolve that
                    unset($_POST['Translate']['language_id']);
                    //Save records

                    if ($model->save()){
                        //Return id from event table after that, assign for translate object
                        
                        foreach ($_POST['Translate'] as $key => $value) {
                            $language = Language::model()->findByAttributes(array('language_code' => $key));
                            $translates = new Translate();

                            $translates->attributes = $value;
                            $translates->event_id = $model->id;
                            $translates->language_id = $language['id'];
                            $translates->save();
                        }
                        $this->redirect(Yii::app()->createAbsoluteUrl('/bookingsystem/event'));
                    }
                }
            }

            $this->render('create', array(
                'model' => $model,
                'translate' => $translate,
                'data' => $item,
            ));
        } catch (Exception $e) {
            Yii::log("Invalid request. Please do not repeat this request again.");
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    public function actionUpdate($id) {
        try {
            $model = $this->loadModel($id);
            $item = new Item('search');
            $item->unsetAttributes();
            if(isset($_GET['Item'])) {
                $item->attributes = $_GET['Item'];
            }
            $language = Language::model()->findAll();
            date_default_timezone_set('UTC');
            $date = date('Y-m-d H:i:s');
            $event_datetime = date("Y-m-d H:i:s",strtotime($model->start_date . $model->start_time));
            //Check event has been expired
            if ($event_datetime < $date) {
                $message = "Cannot edit event because it has been experied";
                $this->render('update',array('message' => $message));
                Yii::app()->end();
            }else{
                if (isset($_POST['Event'])) {
                    $model->attributes = $_POST['Event'];
                    $model->event_code = trim($_POST['Event']['event_code']);
                    $objectFile = CUploadedFile::getInstance($model, 'fileImage');
                    $cover_image = CUploadedFile::getInstance($model, 'cover_image');
                    if ($objectFile)
                        $model->fileImage = 'map_' . md5(time()) . '.' . $objectFile->getExtensionName();
                    // if ($cover_image)
                    //     $model->cover_image = 'cover_' . md5(time()) . '.' . $cover_image->getExtensionName();
                    $model->validate();
                    if (!$model->hasErrors()) {

                        $tagTmp = (isset($_POST['Event']['tag'])) ? $_POST['Event']['tag'] : '';
                        $tag = MyFunctionCustom::addMoreTag($model, $tagTmp);
                        $model->tag = (is_null($tag)) ? json_encode(array()) : json_encode($tag);
                        if ($objectFile) {
                            //delete File
                            MyFunctionCustom::DeleteFile($model, 'map', 'map');
                            $model->map = MyFunctionCustom::saveMap($model, $objectFile);
                        }
                        // if ($cover_image) {
                        //     //delete File
                        //     MyFunctionCustom::DeleteFile($model, 'cover_image', 'cover');
                        //     $model->cover_image = MyFunctionCustom::saveCover($model, $cover_image);
                        // }

                        if ($model->save())
                            $this->redirect(Yii::app()->createAbsoluteUrl('bookingsystem/event'));
                    }
                }else {
                    if ($model->tag != '')
                        $model->tag = MyFunctionCustom::getTag($model->tag);
                }
            }


            if ($model)
                $model->start_date = date('d-m-Y', strtotime($model->start_date));
            $this->render('update', array(
                'model' => $model,
                'language' => $language,
                'parentUrl' => $this->parentUrl,
                'data' => $item,
            ));
        } catch (Exception $e) {
            Yii::log("Invalid request. Please do not repeat this request again.");
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    public function actionDelete($id) {
        try {
            $model = $this->loadModel($id);
            if ($model) {
                // var_dump($model);die();
                    MyFunctionCustom::DeleteFile($model, 'map', 'map');
                    // MyFunctionCustom::DeleteFile($model, 'cover_image', 'cover');
                    // $event = Translate::model()->findAllByAttributes(array('event_id' => $model->id));
                    // $ticket = Ticket::model()->findAllByAttributes(array('event_id' => $model->id));
                    // var_dump($event);die();
                    Translate::model()->deleteAll('`event_id` = :event_id',array(
                        ':event_id'=>$model->id,
                    ));
                    Ticket::model()->deleteAll('`event_id` = :event_id',array(
                        ':event_id'=>$model->id,
                    ));
                    // if ($ticket != null) {
                    //     $ticket->delete();
                    // }
                    // if ($event != null) {
                    //     foreach ($event as $key => $value) {
                    //         $event->delete($value->id);
                    //     }
                        
                    // }                  
                    
                if ($model->delete()) {
                    $this->redirect(Yii::app()->createAbsoluteUrl($this->parentUrl . '/index'));
                }
            }
            else
                throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        } catch (Exception $e) {
            Yii::log("Invalid request. Please do not repeat this request again.");
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    public function actionIndex($expired = null) {
        try {
            if(isset($_POST['status'])){
                $expired = $_POST['status'];
            }else{
                $expired = STATUS_ACTIVE;
            }
            $model = new Event();
            $data = $model->getAll($expired);
            $this->render('index', array(
                'data' => $data, 
                'parentUrl' => $this->parentUrl,
                'status' => $expired
            ));
        } catch (Exception $e) {
            Yii::log("Invalid request. Please do not repeat this request again.");
            echo "<pre>";
            var_dump($e);
            echo "</pre>";
            die();
        }
    }

    public function loadModel($id) {
        try {
            $model = Event::model()->findByPk($id);
            if ($model === null)
                throw new CHttpException(404, 'The requested page does not exist.');
            return $model;
        } catch (Exception $e) {
            Yii::log("Invalid request. Please do not repeat this request again.");
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }
    public function actionUpdate_lang($id,$event)
    {
//        try{
            $model = Translate::model()->with(array('event','language'))->findByAttributes(array('language_id' => $id,'event_id' => $event));
            
            //Edit language
            if (isset($_POST['Translate']['id'])) {
                $translate_data_exist = Translate::model()->findByPk($_POST['Translate']['id']);
                $translate_data_exist->attributes = $_POST['Translate'];
                $translate_data_exist->save();
                $this->redirect(Yii::app()->createAbsoluteUrl('bookingsystem/event'));
            }
            if (isset($_POST['Translate']['event_id'])) {
                $translate = new Translate();
                $translate->attributes = $_POST['Translate'];
                $translate->save();
                $this->redirect(Yii::app()->createAbsoluteUrl('bookingsystem/event'));
            }
            // var_dump($model);die();
            if (isset($model)) {
                $this->render('update_lang',array('model' => $model));
            }
            else{
                $translate = new Translate();
                $event = Event::model()->findByPk($event);
                $language = Language::model()->findByPk($id);
                $this->render('new_lang',array(
                    'translate' => $translate,
                    'event' => $event,
                    'language' => $language
                ));
            }
            
//        }catch(Exception $e){
//            // var_dump($e);die();
//            Yii::log("Invalid request. Please do not repeat this request again.");
//            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
//        }
    }
    public function actionActive()
    {
        if (isset($_POST['event_id'])) {
            $event = Event::model()->findByPk($_POST['event_id']);
            $event->active_status = STATUS_ACTIVE;
            $event->save();
            echo CJSON::encode(1);
            Yii::app()->end();
        }
    }
    public function actionInactive()
    {
        if (isset($_POST['event_id'])) {
            $event = Event::model()->findByPk($_POST['event_id']);
            $event->active_status = STATUS_INACTIVE;
            $event->save();
            echo CJSON::encode(1);
            Yii::app()->end();
        }
    }

}
